package com.example.web.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.web.SysConst;
import com.example.web.dto.*;
import com.example.web.dto.query.*;
import com.example.web.entity.*;
import com.example.web.mapper.*;
import com.example.web.service.*;
import com.example.web.tools.dto.*;
import com.example.web.tools.exception.CustomException;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import lombok.SneakyThrows;
import com.example.web.tools.*;
/**
 * 购物车功能实现类
 */
@Service
public class BuyCardServiceImpl extends ServiceImpl<BuyCardMapper, BuyCard> implements BuyCardService {

	 /**
     * 操作数据库AppUser表mapper对象
     */
    @Autowired
    private AppUserMapper _AppUserMapper;
    /**
     * 操作数据库的BuyCard表mapper对象
     */
    @Autowired
    private BuyCardMapper _BuyCardMpper;

 			
			
 			
    @Autowired
    private GoodMapper _GoodMapper;                        
			

    /**
     * 购物车分页查询
     */
    @SneakyThrows
    @Override
    public PagedResult<BuyCardDto> List(BuyCardPagedInput input) {

      
        //声明一个支持购物车查询的(拉姆达)表达式
        LambdaQueryWrapper<BuyCard> queryWrapper = Wrappers.<BuyCard>lambdaQuery()
                .eq(input.getId()!=null&&input.getId()!=0,BuyCard::getId,input.getId())
                .eq(input.getCreatorId()!=null,BuyCard::getCreatorId,input.getCreatorId());
      
     	 //如果前端搜索传入GoodId不为空,则进行精确查询
        if(input.getGoodId()!=null) {
            queryWrapper=queryWrapper.eq(BuyCard::getGoodId,input.getGoodId());
       	 }
     	 //如果前端搜索传入UserId不为空,则进行精确查询
        if(input.getUserId()!=null) {
            queryWrapper=queryWrapper.eq(BuyCard::getUserId,input.getUserId());
       	 }
      
        //按创建时间从大到小排序 最新的显示在最前面
        queryWrapper=queryWrapper.orderByDesc(BuyCard::getCreationTime);
        //构建一个分页查询的model
        Page<BuyCard> page = new Page<>(input.getPage(), input.getLimit());
          
   
         //从数据库进行分页查询获取购物车数据
        IPage<BuyCard> pageRecords= _BuyCardMpper.selectPage(page, queryWrapper);

        //获取所有满足条件的数据行数
        Long totalCount= _BuyCardMpper.selectCount(queryWrapper);

        //把BuyCard实体转换成BuyCard传输模型
        List<BuyCardDto> items= Extension.copyBeanList(pageRecords.getRecords(),BuyCardDto.class);
        for (BuyCardDto item : items) {
          
          //查询出关联的创建用户信息
            AppUserDto  CreatorAppUserDTO=new AppUserDto();
            AppUser  CreatorAppUserEntity= _AppUserMapper.selectOne(Wrappers.<AppUser>lambdaQuery().eq(AppUser::getId,item.getCreatorId()));
           if(CreatorAppUserEntity!=null) {
                BeanUtils.copyProperties(CreatorAppUserDTO, CreatorAppUserEntity);
                item.setCreatorAppUserDto(CreatorAppUserDTO);
            }  
         
           
          	            
           //查询出关联的AppUser表信息
           AppUserDto UserDTO = new AppUserDto();        
            AppUser  UserEntity= _AppUserMapper.selectOne(Wrappers.<AppUser>lambdaQuery().eq(AppUser::getId,item.getUserId()));
           if(UserEntity!=null) {  
          BeanUtils.copyProperties(UserDTO,UserEntity);
            item.setUserDto(UserDTO); 
           }
          
           
          	            
           //查询出关联的Good表信息
           GoodDto GoodDTO = new GoodDto();        
            Good  GoodEntity= _GoodMapper.selectOne(Wrappers.<Good>lambdaQuery().eq(Good::getId,item.getGoodId()));
           if(GoodEntity!=null) {  
          BeanUtils.copyProperties(GoodDTO,GoodEntity);
            item.setGoodDto(GoodDTO); 
           }
          
        }
      
        //返回一个分页结构给前端
        return PagedResult.GetInstance(items,totalCount);

    }
  
    /**
     * 单个购物车查询
     */
    @SneakyThrows
    @Override
    public BuyCardDto Get(BuyCardPagedInput input) {
       if(input.getId()==null)
        {
            return new BuyCardDto();
        }
        PagedResult<BuyCardDto>  pagedResult =List(input);
        return pagedResult.getTotalCount()>0?pagedResult.getItems().stream().findFirst().get():new BuyCardDto();
    }

    /**
     *购物车创建或者修改
     */
    @SneakyThrows
    @Override
    public BuyCardDto CreateOrEdit(BuyCardDto input) {

        if(input.getId()==null||input.getId()==0)
        {
            Integer userId = BaseContext.getCurrentUserDto().getUserId();
            List<BuyCard> list = _BuyCardMpper.selectList(null).stream().filter(x -> x.getUserId() == userId && x.getGoodId() == input.getGoodId()).toList();
           if(list.stream().count()>0)
           {
               throw new CustomException("该商品已存在购物车,请勿重复添加");
           }
        }
        //声明一个购物车实体
        BuyCard BuyCard = new BuyCard();

        //把前端传入的input参数拷贝到购物车实体
        BeanUtils.copyProperties(BuyCard,input);

        //调用数据库的增加或者修改方法
        saveOrUpdate(BuyCard);

        //定义一个返回给前端的购物车传输模型
        BuyCardDto BuyCardDto=new BuyCardDto();

        //同理把操作的购物车实体拷贝给购物车传输模型
        BeanUtils.copyProperties(BuyCardDto,BuyCard);

        //把传输模型返回给前端
        return BuyCardDto;
    }



}
